{include file="header.html"}
<link type="text/css" href="/js/easemob/ease-chat.css" rel="stylesheet" />
<body class="gr">

<div class="navBar">
	<a class="left" href="javascript:history.go(-1)"><i class="return"></i></a>
	<div class="titleView">商富商城客服</div>
</div>

<div class="chat-talk main-top main-bottom">
	<textarea id="result" style="display:none;">{json_encode($data.result)}</textarea>
	{if $member->id}
	<input type="hidden" id="my_id" value="{$member->id}" />
	<input type="hidden" id="my_name" value="{$member->name}" />
	<input type="hidden" id="my_avatar" value="{$member->avatar}" />
	<input type="hidden" id="chatter_id" value="yanglanzi" />
	<input type="hidden" id="chatter_name" value="{$data.chatter_name}" />
	<input type="hidden" id="chatter_avatar" value="{$data.chatter_avatar}" />
	{/if}
	<ul class="ease-chat"></ul>
</div>

{if $member->id}
<div class="ease-chat-overlay"></div>
<div class="ease-chat-toolbar">
	<div class="view">
		<a href="javascript:void(0)" class="more"></a>
		<a href="javascript:void(0)" class="send">发送</a>
		<a href="javascript:void(0)" class="emoji"></a>
		<a href="javascript:void(0)" class="audio"></a>
		<div><input type="text" id="msg" placeholder="输入新消息" /></div>
	</div>
	<div class="area">
		<a href="javascript:void(0)" class="image"><input type="file" id="image_file" /></a>
		<a href="javascript:void(0)" class="goods"></a>
	</div>
</div>
{/if}

</body>
</html>
<script type="text/javascript" src="/js/easemob/strophe.js"></script>
<script type="text/javascript" src="/js/easemob/websdk-1.1.2.js"></script>
<script type="text/javascript" src="/js/easemob/webim.config.js"></script>
<script type="text/javascript" src="/js/easemob/webim.action.js"></script>
<script>
var isKefu = true;
var interface, ul, toolbar, overlay, input, my_id, my_name, my_avatar, chatter_id, chatter_name, chatter_avatar, goods_id, goods_name, goods_image;
function toggleMore(showOrHide){
	if(typeof showOrHide=='undefined'){
		if(toolbar.hasClass('show')){
			toolbar.removeClass('show').find('.more').removeClass('this');
			overlay.removeClass('show');
			interface.removeClass('show');
		}else{
			toolbar.addClass('show').find('.more').addClass('this');
			overlay.addClass('show');
			interface.addClass('show');
		}
		return;
	}
	if(showOrHide){
		toolbar.addClass('show').find('.more').addClass('this');
		overlay.addClass('show');
		interface.addClass('show');
	}else{
		toolbar.removeClass('show').find('.more').removeClass('this');
		overlay.removeClass('show');
		interface.removeClass('show');
	}
}
$(function(){
	{if $member->id}
	var accessToken = '{$data.token}';
	WebIM.action.login({
		username: '{$member->id}',
		password: '{$member->origin_password}',
		accessToken: accessToken,
		callback: function(token){
			if(accessToken==token)return;
			$.post('api.php?app=chat&act=save_token', { token:token });
		}
	});
	{/if}
	
	interface = $('.chat-talk');
	ul = $('.ease-chat');
	toolbar = $('.ease-chat-toolbar');
	overlay = $('.ease-chat-overlay');
	input = toolbar.find('#msg');
	my_id = $('#my_id').val();
	my_name = $('#my_name').val();
	my_avatar = $('#my_avatar').val();
	chatter_id = $('#chatter_id').val();
	chatter_name = $('#chatter_name').val();
	chatter_avatar = $('#chatter_avatar').val();
	goods_id = $('.chat-talk #goods_id').val();
	goods_name = $('.chat-talk #goods_name').val();
	goods_image = $('.chat-talk #goods_image').val();
	
	//if(!$.browser.wechat){
		toolbar.find('.view').addClass('view-web');
	//}
	
	//if(!goods_id.length)toolbar.find('.area .goods').hide();
	toolbar.find('.more').click(function(){
		toggleMore();
	});
	overlay.click(function(){
		toggleMore();
	});
	input.focus(function(){
		toggleMore(false);
	}).keyup(function(e){
		var e = e||window.event, code = e.which||e.keyCode;
		if(code==13)sendText();
	});
	
	toolbar.find('.send').click(function(){
		sendText();
	});
	toolbar.find('#image_file').change(function(){
		toggleMore(false);
		sendImage();
	});
	toolbar.find('.area .goods').hide().click(function(){
		sendText(goods_name, true);
		toggleMore(false);
	});
	
	var result = [], html = '';
	if($('.chat-talk #result').val().length)result = $.formatJSON($('.chat-talk #result').val());
	if($.isArray(result)){
		for(var i=0; i<result.length; i++){
			html += returnMsg(result[i]);
		}
		handleObj(ul.html(html));
		setTimeout(function(){
			$('.chat-talk').scrollTop($('.chat-talk')[0].scrollHeight);
		}, 10);
	}
});

//环信================================================================
function returnMsg(r) {
	var msg = '', isSender = r.from==my_id, reverse = isSender ? 'reverse' : '', name = '', avatar = '',
		ext = { member_id:'', name:'', avatar:'', chatter_name:'', chatter_avatar:'', goods:'' };
	if($.isPlainObject(r.payload.ext)){
		ext = $.extend(ext, r.payload.ext);
		if ($.isPlainObject(ext.weichat) && $.isPlainObject(ext.weichat.agent)) {
			name = ext.weichat.agent.userNickname;
			avatar = ext.weichat.agent.avatar;
		} else if (ext.name) {
			name = ext.name;
			avatar = ext.avatar;
		}
	}
	switch(r.payload.bodies[0].type){
		case 'txt':
			if($.isPlainObject(ext.goods)){
				content = '<a href="/wap.php?app=goods&act=detail&goods_id='+ext.goods.goods_id+'" target="_blank"><img src="'+ext.goods.goods_image+'" height="90" /><div>'+ext.goods.goods_name+'</div></a>';
			}else{
				msg = r.payload.bodies[0].msg;
			}
			break;
		case 'img':
			var ow = 0, oh = 0, w = ow, h = oh, objId = new Date().time()+''+rndCode(3);
			if($.isPlainObject(r.payload.bodies[0].size)){
				ow = r.payload.bodies[0].size.width;
				oh = r.payload.bodies[0].size.height;
				w = ow;
				h = oh;
				if(h>90){
					w = 90 * w / h;
					h = 90;
				}
			}
			msg = '<img src="/js/easemob/images/space.gif" id="'+objId+'" width="'+w+'" height="'+h+'" ow="'+ow+'" oh="'+oh+'" />\
				<div style="background:url(/js/easemob/images/loading.gif) no-repeat center center;background-size:cover;\
				position:absolute;left:50%;top:50%;margin-left:-16px;margin-top:-16px;width:32px;height:32px;"></div>';
			WebIM.action.downloadFile({
				url: r.payload.bodies[0].url,
				secret: r.payload.bodies[0].secret,
				complete: function(src){
					$('#'+objId).attr('src', src).next().remove();
					$('#'+objId).error(function(){
						var html = '<div style="background:url(/images/nopic.png) no-repeat center center;background-size:cover;\
							position:absolute;left:50%;top:50%;margin-left:-25px;margin-top:-25px;width:50px;height:50px;"></div>';
						$('#'+objId).attr('src', '/js/easemob/images/space.gif').after(html);
					});
				},
				error: function(){
					$('#'+objId).next().css({ 'background-image':'/images/nopic.png', width:50, height:50, 'margin-left':'-25px', 'margin-top':'-25px;' });
				}
			});
			break;
		case 'loc':
			msg = '<img src="/js/easemob/images/location.png" width="95" lat="'+r.payload.bodies[0].lat+'" lng="'+r.payload.bodies[0].lng+'" />\
				<div style="position:absolute;left:8px;bottom:8px;width:110%;height:33px;text-align:left;color:#fff;font-size:12px;\
				overflow:hidden;-webkit-transform:scale(0.75);transform:scale(0.75);-webkit-transform-origin:left;transform-origin:left;">\
				'+r.payload.bodies[0].addr+'</div>';
			break;
		case 'audio':
			var objId = new Date().time()+''+rndCode(3);
			msg = '<div id="'+objId+'" style="width:150px;height:25px;overflow:hidden;"></div>';
			WebIM.action.downloadFile({
				url: r.payload.bodies[0].url,
				secret: r.payload.bodies[0].secret,
				headers: { 'Accept':'audio/mp3' },
				complete: function(src){
					var html = '<audio controls="true" width="150" height="25"><source src="'+src+'"><font>我发送了语音，用APP客户端查看吧</font></audio>';
					$('#'+objId).html(html);
				},
				error: function(){
					$('#'+objId).html('<font>我发送了语音，用APP客户端查看吧</font>');
				}
			});
			break;
		case 'video':
			msg = '<font>我发送了视频，用APP客户端查看吧</font>';
			break;
	}
	return '<li>\
				<div class="row '+reverse+'">\
					<div class="l">\
						<div class="avatar" '+(avatar?'style="background-image:url('+avatar+');"':'')+'></div>\
					</div>\
					<span>'+name+'</span>\
					<div class="r">'+msg+'</div>\
					<div class="clear"></div>\
				</div>\
			</li>';
}
function appendMsg(from, to, data, isGoods) {
	var ext = getExt(isGoods);
	if(!$.isPlainObject(data))data = { ext:ext, bodies:[{ type:'txt', msg:data }] };
	var html = $(returnMsg({
		from : from,
		to : to,
		payload : data
	}));
	if(html.length)ul.append(html);
	handleObj(html);
	setTimeout(function(){
		$('.chat-talk').animate({ scrollTop:$('.chat-talk')[0].scrollHeight }, 2000, 'easeout');
	}, 10);
}
function getExt(isGoods){
	var ext = { member_id:my_id, name:my_name, avatar:my_avatar, chatter_name:chatter_name, chatter_avatar:chatter_avatar, goods:'' };
	if(isGoods){
		if($.isPlainObject(isGoods)){
			ext = $.extend(ext, { goods_id:isGoods.goods_id, goods_name:isGoods.goods_name, goods_image:isGoods.goods_image });
		}else{
			ext = $.extend(ext, { goods_id:goods_id, goods_name:goods_name, goods_image:goods_image });
		}
	}
	if(isKefu){
		var weichat = {
			visitor: { trueName:my_name, userNickname:my_name, qq:'', email:'' }
		};
		//weichat.agentUsername = '客服登录的邮箱';//在普通聊天时转接给指定的客服
		ext.weichat = weichat;
	}
	return ext;
}
function handleObj(parent){
	parent.find('img[lat]').click(function(){
		var _this = $(this), lat = _this.attr('lat'), lng = _this.attr('lng');
		location.href = 'wap.php?app=other&act=map&latitude='+lat+'&longitude='+lng;
	});
	parent.find('img[ow]').click(function(){
		var _this = $(this), ow = _this.attr('ow')*1, oh = _this.attr('oh')*1, w = $.window().width-5*2, h = 0, img = new Image();
		if(ow<w)w = ow;
		h = w * oh / ow;
		$(img).attr('src', _this.attr('src')).click(function(){
			$.overlay(false);
		});
		$(img).load(function(){
			$.overlay($(img), 0, function(){
				this.css({ width:w, height:h });
			});
		});
	});
}

//发送文字
function sendText(text, isGoods) {
	var msg = text || input.val();
	var options = {
		to : chatter_id,
		msg : msg,
		ext : getExt(isGoods),
		sendComplete : function(msgId, payload){
			$.postJSON('api.php?app=chat&act=insert', { msg_id:msgId, to:chatter_id, payload:$.jsonString(payload) }, function(json){
				if(json.error!=0){ $.overloadError(json.msg);return }
				msg = msg.replace(/\n/g, '<br />');
				appendMsg(my_id, chatter_id, msg, isGoods);
				if (typeof(text)=='undefined') input.val('').focus();
			});
		}
	};
	WebIM.action.sendText(options);
}
//发送图片
function sendImage() {
	var fileInputId = 'image_file';
	var options = {
		input : fileInputId,
		to : chatter_id,
		ext : getExt(),
		uploadError : function(e) {
			$.overloadError('发送图片失败');
		},
		sendComplete : function(msgId, payload) {
			$.postJSON('api.php?app=chat&act=insert', { msg_id:msgId, to:chatter_id, payload:$.jsonString(payload) }, function(json){
				if(json.error!=0){ $.overloadError(json.msg);return }
				appendMsg(my_id, chatter_id, payload.bodies[0]);
			});
		}
	};
	WebIM.action.sendImage(options);
}
//发送音频
function sendAudio() {
	$.overload('正在处理中');
	$.getJSON('api.php?app=chat&act=sendAudio', { media_id:localId }, function(json){
		localId = null;
		if(json.error!=0){ $.overloadError(json.msg);return }
		var options = {
			to : chatter_id,
			ext : getExt(),
			url : json.url,
			secret : json.secret
		};
		WebIM.action.sendAudio(options);
		appendMsg(my_id, chatter_id, {
			type : 'audio',
			url : json.url
		});
		$.overload(false);
	});
}

//接收消息
WebIM.action = $.extend(WebIM.action, {
	receiveText: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			msg: message.msg
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveEmoji: function(message){
		
	},
	receiveImage: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			url: message.url,
			secret: message.secret,
			size : message.size
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveLocation: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			addr: message.addr,
			lat: message.lat,
			lng: message.lng
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveAudio: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			url: message.url,
			secret: message.secret,
			length: message.length,
			file_length: message.file_length
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveVideo: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			url: message.url,
			secret: message.secret,
			length: message.length,
			file_length: message.file_length,
			thumb: message.thumb,
			thumb_secret: message.thumb_secret
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveFile: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			url: message.url,
			secret: message.secret,
			filename: message.filename,
			file_length: message.file_length
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	},
	receiveCmd: function(message){
		var payload = { ext:message.ext, bodies:[{
			type: message.type,
			msg: message.msg,
			action: message.action
		}] };
		$.postJSON('api.php?app=chat&act=insert', { msg_id:message.id, from:chatter_id, payload:$.jsonString(payload) }, function(json){
			if(json.error!=0){ $.overloadError(json.msg);return }
			var isGoods = false;
			if($.isPlainObject(message.ext) && $.isPlainObject(message.ext.goods)){
				isGoods = { goods_id:message.ext.goods.goods_id, goods_name:message.ext.goods.goods_name, goods_image:message.ext.goods.goods_image };
			}
			appendMsg(message.from, message.to, payload, isGoods);
		});
	}
});
</script>

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
/*
var localId = null, rTimer = null;
wx.config({
	debug: false,
	appId: "{$weixin_sign_package.appId}",
	timestamp: "{$weixin_sign_package.timestamp}",
	nonceStr: "{$weixin_sign_package.nonceStr}",
	signature: "{$weixin_sign_package.signature}",
	jsApiList: [
		'startRecord',
		'stopRecord',
		'uploadVoice'
	]
});
wx.ready(function(){
	$('.ease-chat-toolbar .view .audio').click(function(){
		rTimer = setTimeout(stopRecord, 58000);
		wx.startRecord();
		showOverlay();
	});
	function stopRecord(){
		clearTimeout(rTimer); rTimer = null;
		wx.stopRecord({
			success: function(res){
				localId = res.localId;
				uploadAudio();
			}
		});
		hideOverlay();
	}
	function uploadAudio(){
		$.overload(null);
		wx.uploadVoice({
			localId: localId, //需要上传的音频的本地ID，由stopRecord接口获得
			isShowProgressTips: 0, //默认为1，显示进度提示
			success: function(res){
				localId = res.serverId; //返回音频的服务器端ID
				sendAudio();
			}
		});
	}
	function showOverlay(type){
		var window = $.window(), overlay = $('<div class="record-overlay"></div>').css({ display:'none' });
		$(document.body).append(overlay);
		switch(type){
			case 1:
				overlay.html('<div><font>播放录音中</font></div>').onclick(function(){
					wx.stopVoice({ localId:recordId });
					hideOverlay();
				});
				break;
			default:
				overlay.html('<div><span></span><font>录音中，点击完成</font></div><a href="javascript:void(0)">取消录音</a>');
				overlay.find('div').onclick(stopRecord);
				overlay.find('a').click(function(){
					clearTimeout(rTimer); rTimer = null;
					localId = null;
					hideOverlay();
					wx.stopRecord();
				});
				break;
		};
		var div = overlay.find('div');
		div.css('margin-top', (window.height-div.height())/2-50);
		overlay.fadeIn(300);
	}
	function hideOverlay(){
		$('.record-overlay').removeOut(300);
	}
});
*/
</script>
